/**
 * 初始化IndexedDB数据库实例
 */
function openIndexedDB(dbName, version = 1) {
    return new Promise((resolve, reject) => {
        var indexedDB =
            window.indexedDB ||
            window.mozIndexedDB ||
            window.webkitIndexedDB ||
            window.msIndexedDB;
        let db;
        const request = indexedDB.open(dbName, version);
        request.onsuccess = function (event) {
            db = event.target.result;
            resolve(db);
        };
        request.onerror = function (event) {
            console.log("数据库打开报错");
        };
        request.onupgradeneeded = function (event) {
            console.log("onupgradeneeded");
            db = event.target.result;
            db.createObjectStore("chatUser", {
                keyPath: "contactId",
            });
            db.createObjectStore("user", {
                keyPath: "userId",
            });
            var objectStore = db.createObjectStore("message", {
                keyPath: "messageId",
            });
            objectStore.createIndex("chatId", "chatId", {
                unique: false
            });
        };
    });
}

function addDb(db, storeName, data) {
    var request = db.transaction([storeName], "readwrite").objectStore(storeName).add(data);
    request.onsuccess = function (event) {
        console.log("数据写入成功");
    };
    request.onerror = function (event) {
        console.log("数据写入失败");
    };
}

function getDataByKey(db, storeName, key) {
    return new Promise((resolve, reject) => {
        var transaction = db.transaction([storeName]);
        var objectStore = transaction.objectStore(storeName);
        var request = objectStore.get(key);
        request.onerror = function (event) {
            console.log("事务失败");
        };
        request.onsuccess = function (event) {
            console.log("主键查询结果: ", request.result);
            resolve(request.result);
        };
    });
}

function getAllData(db, storeName) {
    return new Promise((resolve, reject) => {
        let list = [];
        var store = db.transaction(storeName, "readwrite").objectStore(storeName);
        var request = store.openCursor();
        request.onsuccess = function (e) {
            var cursor = e.target.result;
            if (cursor) {
                list.push(cursor.value);
                cursor.continue();
            } else {
                resolve(list)
            }
        };
    });
}

function getData(db, storeName, indexName, indexValue) {
    return new Promise((resolve, reject) => {
        let list = [];
        var store = db.transaction(storeName, "readwrite").objectStore(storeName);
        var request = store.index(indexName).openCursor(IDBKeyRange.only(indexValue));
        request.onsuccess = function (e) {
            var cursor = e.target.result;
            if (cursor) {
                list.push(cursor.value);
                cursor.continue();
            } else {
                resolve(list)
            }
        };
        request.onerror = function (e) {};
    })
}

function updateDB(db, storeName, data) {
    var request = db.transaction([storeName], "readwrite").objectStore(storeName).put(data);
    request.onsuccess = function () {
        // console.log("数据更新成功");
    };
    request.onerror = function () {
        // console.log("数据更新失败");
    };
}

function deleteDB(db, storeName, id) {
    var request = db.transaction([storeName], "readwrite").objectStore(storeName).delete(id);
    request.onsuccess = function () {
        // console.log("数据删除成功");
    };
    request.onerror = function () {
        console.log("数据删除失败");
    };
}

function cursorDelete(db, storeName, indexName, indexValue) {
    var store = db.transaction(storeName, "readwrite").objectStore(storeName);
    var request = store.index(indexName).openCursor(IDBKeyRange.only(indexValue));
    request.onsuccess = function (e) {
        var cursor = e.target.result;
        var deleteRequest;
        if (cursor) {
            deleteRequest = cursor.delete();
            deleteRequest.onerror = function () {
                console.log("游标删除该记录失败");
            };
            deleteRequest.onsuccess = function () {
                // console.log("游标删除该记录成功");
            };
            cursor.continue();
        }
    };
    request.onerror = function (e) {};
}

function getDataByIndexAndPage(db, storeName, indexName, indexValue, page) {
    return new Promise((resolve, reject) => {
        let list = [];
        let pageSize = 20;
        let counter = 0;
        let advanced = true;
        var store = db.transaction(storeName, "readwrite").objectStore(storeName);
        var request = store.index(indexName).openCursor(IDBKeyRange.only(indexValue), 'prev');
        request.onsuccess = function (e) {
            var cursor = e.target.result;
            if (page > 1 && advanced) {
                advanced = false;
                cursor.advance((page - 1) * pageSize);
                return;
            }
            if (cursor) {
                list.push(cursor.value);
                counter++;
                if (counter < pageSize) {
                    cursor.continue();
                } else {
                    cursor = null;
                    // console.log("分页查询列表：",  list);
                    resolve({
                        list: list
                    })
                }
            } else {
                // console.log("分页查询结果", list);
                resolve({
                    list: list
                })
            }
        };
        request.onerror = function (e) {};
    })
}

export {
    openIndexedDB,
    addDb,
    getDataByKey,
    getAllData,
    getData,
    updateDB,
    deleteDB,
    cursorDelete,
    getDataByIndexAndPage
}
